/**
 * 
 */
package com.taobao.client.component.pages;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;

/**
 * 分页组建
 * 
 * Pages p = new Pages(){
 * 		void go(page);
 * };

 */
/**
 * 
 * 
 * @author jiangyongyuan
 */
public class Pages extends Composite implements ClickHandler {

	public static final int VISIBLE_ITEM_COUNT = 4;
	int TOTAL = 4;
	int current = 1;
	
	private HTML countLabel = new HTML();
	private HTML newerButton = new HTML(
			"<a href='javascript:;'>&lt; newer</a>", true);
	private HTML olderButton = new HTML(
			"<a href='javascript:;'>older &gt;</a>", true);
	private int startIndex/* , selectedRow = -1 */;

	private HorizontalPanel navBar = new HorizontalPanel();

	public Pages(int total) {
		this.TOTAL = total;
		
		newerButton.addClickHandler(this);
		olderButton.addClickHandler(this);

		// Create the 'navigation' bar at the upper-right.
		HorizontalPanel innerNavBar = new HorizontalPanel();

		innerNavBar.add(newerButton);
		innerNavBar.add(countLabel);
		innerNavBar.add(olderButton);

		navBar.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		navBar.add(innerNavBar);
		navBar.setWidth("100%");

		initWidget(navBar);
		update();
	}

	@Override
	public void onClick(ClickEvent arg0) {
		Object sender = arg0.getSource();
		if (sender == olderButton) {
			// Move forward a page.
			startIndex += VISIBLE_ITEM_COUNT;
			if (startIndex >= TOTAL) {
				startIndex -= VISIBLE_ITEM_COUNT;
			} else {
				update();
			}
		} else if (sender == newerButton) {
			// Move back a page.
			startIndex -= VISIBLE_ITEM_COUNT;
			if (startIndex < 0) {
				startIndex = 0;
			} else {
				update();
			}
		}
	}

	private void update() {
		// Update the older/newer buttons & label.
		// int count = MailItems.getMailItemCount();
		int count = TOTAL;
		
		if(startIndex == 0)
			current = 1;
		else
			current = startIndex / VISIBLE_ITEM_COUNT + 1;
		
		int max = startIndex + VISIBLE_ITEM_COUNT;
		if (max > count) {
			max = count;
		}

		newerButton.setVisible(startIndex != 0);
		olderButton.setVisible(startIndex + VISIBLE_ITEM_COUNT < count);
		countLabel
				.setText("" + (startIndex + 1) + " - " + max + " of " + count);

		go(current );
		// Show the selected emails.
	}
	
	/**
	 * 由使用者自行执行分页处理
	 * @param current
	 */
	protected void go(int current){
		
	}
}
